import axios from 'axios';
import { Toast } from 'vant';
console.log(process.env);
export const baseURL = process.env.VUE_APP_API_URL;
import { getToken, removeToken } from './auth';
/**
 * 异常处理程序
 */

/**
 * 配置request请求时的默认参数
 */
const request = axios.create({
  baseURL,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=utf-8'
  },
  timeout: 10000 // 请求超时时间
});

request.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

/**
 * 对于状态码实际是 200 的错误
 */
request.interceptors.response.use(
  (response) => {
    const { data } = response;
    const { code, message } = data;
    if (code !== '000000') {
      Toast(message || '系统异常');
      if (['100001'].includes(code)) {
        removeToken();
        location.reload();
      }
      return Promise.reject(data);
    }
    return data;
  },
  (error) => {
    const { response = {} } = error;
    const { data = {} } = response;
    const { code, message } = data;
    if (code !== '000000' && process.env.NODE_ENV !== 'development') {
      Toast(message || '系统异常');
      if (['100001'].includes(code)) {
        removeToken();
        location.reload();
      }
      return Promise.reject(data);
    }
    return Promise.reject(error);
  }
);

export default request;
